/*
 *  ptclRecvData.cpp
 *  serialExample
 *
 *  Created by Motoi Ishibashi on 11/02/28.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "ptclRecvData.h"

ptclRecvData::ptclRecvData()
{
	bufferIndex = 0;
	bWaitHeader = true;
}

ptclRecvData::~ptclRecvData()
{
	
	
	
}

void ptclRecvData::parseCommand()
{
	if(recvBuffer[0] == 0xB1){
		if(bufferIndex == 4){
			printf("ball No.%d passed checkpoint %d : speed : %02f msec\n",
			recvBuffer[1], recvBuffer[2], (float)recvBuffer[3]/10.0 + 20.0);
//			printf("ball No.%d passed checkpoint %d\n", recvBuffer[1], recvBuffer[2]);
			// 0 , 1 ~ 16 
			// 1 2
			// 3 4
			// 5 6
			int ballID = (int)recvBuffer[1];
//			int checkPointID = (int)recvBuffer[2]== 16 ? 0 : (int)recvBuffer[2];
//			int checkPointID = (int)recvBuffer[2]== 0 ? -1 : (int)recvBuffer[2] - 1;
			int checkPointID;
			
			
			if ((int)recvBuffer[2] == 0) {
				checkPointID = -1;
			}else {
				checkPointID = (int)recvBuffer[2] - 1;
			}
			cout << "recvBuffer[2] " << (int)recvBuffer[2] << " checkPointID " << checkPointID << endl;
			
			if (ballID>200-1) {
				cout << "ballID is above 200(numBall) " << endl;
			}
			
//			cout << "ballID == "<< ballID << endl;
			float speed = (recvBuffer[3] / 10.0) + 20.0;
			sendToMaxPatch(ballID, checkPointID, speed);
			sendToCheckPoints(ballID, checkPointID, speed);
			sendToVisualizer(ballID, checkPointID, speed);
		}
	}
}

//void ptclRecvData::parseCommand()
//{
//	if(recvBuffer[0] == 0xB1){
//		if(bufferIndex == 4){
//			printf("ball No.%d passed checkpoint %d : speed : %02f msec\n",
//				   recvBuffer[1], recvBuffer[2], (float)recvBuffer[3]/10.0 + 20.0);
//			
//		}
//	}
//}

void ptclRecvData::sendToMaxPatch(int _ballID, int _checkPointID, float _speed){
	if(_checkPointID >= 0){	
		ofxDaito::bang("/pass", _ballID, _checkPointID, _speed);	
		ofxDaito::bang("/mute", _ballID, 0);						
//		cout << "checkPointID" << _checkPointID <<endl;						
	}else {
		ofxDaito::bang("/mute", _ballID, 1);	
//		cout << "(maybe - 1)checkPointID" << _checkPointID <<endl;
	}
}

void ptclRecvData::sendToCheckPoints(int _ballID, int _checkPointID, float _speed){
	if(_checkPointID >= 0){		
		checkPoints[_checkPointID]->passing(_ballID, _speed);	
	}
//	void passing(int _ballID, float _speed)	
}

void ptclRecvData::sendToVisualizer(int _ballID, int _checkPointID, float _speed){
	if(_checkPointID >= 0){			
		realBalls[_ballID]->passingCheckPoint(_checkPointID, _speed);
	}	

}

void ptclRecvData::threadedFunction()
{
	while(1){
		
		if(serial->available() > 0){
		
			unsigned char c = serial->readByte();
			if(c == 0xFF && bWaitHeader == true){
				bufferIndex = 0;
				bWaitHeader = false;
			}
			else if(c == 0xFE){
				parseCommand();
				bWaitHeader = true;
				bufferIndex = 0;
			}
			else {
				recvBuffer[bufferIndex] = c;
				bufferIndex ++;
				if (bufferIndex >= PTCL_RECV_MAXBUFFER) {
					bufferIndex = 0;
				}
			}
		
		}
	}

}
